﻿using AutoMapper;
using BS.Domain.RBAC;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;

namespace BS.Write.Api.Handler.RBAC
{
    public class UpdateUserAndRoleCommandHandler : IRequestHandler<UpdateUserToRoleCommand, ApiResult>
    {
        private readonly ILogger<UpdateUserAndRoleCommandHandler> _logger;

        private readonly IUserRepository _userRepository;

        private readonly IRoleRepository _roleRepository;

        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="userRepository"></param>
        /// <param name="roleRepository"></param>
        /// <param name="mapper"></param>
        public UpdateUserAndRoleCommandHandler(ILogger<UpdateUserAndRoleCommandHandler> logger, IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper)
        {
            _logger = logger;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 更新用户角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult> Handle(UpdateUserToRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var usersDto = _mapper.Map<UserInfo>(request);
                var result = await _userRepository.UpdateAsync(usersDto);
                
                return await Task.FromResult(ApiResult.Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error when get user by id");
                return  ApiResult.Fail(ex.Message);
            }
        }
    }
}

/// <summary>
/// 更新用户角色
/// </summary>
public class UpdateUserToRoleCommand:IRequest<ApiResult>
{
    public int UserId { get; set; }

    public string UserName { get; set; } = string.Empty;

    public string Password { get; set; } = string.Empty;

    public int RoleId { get; set; }
}